import Vue from 'vue'
import Vuex from 'vuex'
// ✅ 导入接口（组件或 Store 中）
import { login, logout, getUserInfo } from "@/api/user";

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        user: JSON.parse(localStorage.getItem('userInfo')) || null,
        token: localStorage.getItem('token') || '',
        isLogin: !!localStorage.getItem('token'),
        tabbarActive: 0,
        likedPosts: JSON.parse(localStorage.getItem('likedPosts') || '[]'),
        collectedPosts: JSON.parse(localStorage.getItem('collectedPosts') || '[]'),
        followedUsers: JSON.parse(localStorage.getItem('followedUsers') || '[]'),
        notifications: [],
        notificationCount: 0,
        // 聊天相关状态
        chatMessages: {},  // 存储聊天消息，格式: {userId: [messages]}
        chatSessions: [],  // 聊天会话列表
        currentChatSession: null, // 当前聊天会话
        unreadMessageCount: 0  // 未读消息总数
    },

    getters: {
        isLogin: state => state.isLogin,
        user: state => state.user,
        token: state => state.token,
        tabbarActive: state => state.tabbarActive,
        likedPosts: state => state.likedPosts,
        collectedPosts: state => state.collectedPosts,
        followedUsers: state => state.followedUsers,
        notifications: state => state.notifications,
        notificationCount: state => state.notificationCount,
        // 聊天相关getters
        chatMessages: state => state.chatMessages,
        chatSessions: state => state.chatSessions,
        currentChatSession: state => state.currentChatSession,
        unreadMessageCount: state => state.unreadMessageCount,
        // 获取指定用户的聊天消息
        getChatMessagesWithUser: (state) => (userId) => {
            return state.chatMessages[userId] || []
        }
    },

    mutations: {
        setToken(state, token) {
            state.token = token
            localStorage.setItem('token', token)
            state.isLogin = true
        },
        setUserInfo(state, user) {
            state.user = user
            localStorage.setItem('userInfo', JSON.stringify(user))
        },
        logout(state) {
            state.token = ''
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            state.isLogin = false
            state.user = null
        },
        setTabbarActive(state, index) {
            state.tabbarActive = index
        },
        toggleLikePost(state, postId) {
            const index = state.likedPosts.indexOf(postId)
            if (index === -1) {
                state.likedPosts.push(postId)
            } else {
                state.likedPosts.splice(index, 1)
            }
            localStorage.setItem('likedPosts', JSON.stringify(state.likedPosts))
        },
        toggleCollectPost(state, postId) {
            const index = state.collectedPosts.indexOf(postId)
            if (index === -1) {
                state.collectedPosts.push(postId)
            } else {
                state.collectedPosts.splice(index, 1)
            }
            localStorage.setItem('collectedPosts', JSON.stringify(state.collectedPosts))
        },
        toggleFollowUser(state, userId) {
            const index = state.followedUsers.indexOf(userId)
            if (index === -1) {
                state.followedUsers.push(userId)
            } else {
                state.followedUsers.splice(index, 1)
            }
            localStorage.setItem('followedUsers', JSON.stringify(state.followedUsers))
        },
        addNotification(state, notification) {
            state.notifications.push(notification)
        },
        clearNotifications(state) {
            state.notifications = []
        },
        setNotifications(state, count) {
            state.notificationCount = count
        },

        // 聊天相关mutations
        // 添加聊天消息
        addChatMessage(state, message) {
            const userId = message.isSelf ? message.to : message.from

            // 初始化用户消息数组（如果不存在）
            if (!state.chatMessages[userId]) {
                state.chatMessages[userId] = []
            }

            // 添加消息到数组
            state.chatMessages[userId].push(message)

            // 更新会话列表
            this.commit('updateChatSession', {
                userId: userId,
                lastMessage: message.content,
                lastTime: message.timestamp,
                unread: !message.isSelf
            })

            // 如果不是自己发送的消息，增加未读消息计数
            if (!message.isSelf) {
                state.unreadMessageCount++
            }
        },

        // 更新聊天会话
        updateChatSession(state, { userId, lastMessage, lastTime, unread = false }) {
            // 查找是否已存在该会话
            const sessionIndex = state.chatSessions.findIndex(session => session.userId === userId)

            if (sessionIndex !== -1) {
                // 更新已有会话
                const session = state.chatSessions[sessionIndex]
                state.chatSessions.splice(sessionIndex, 1, {
                    ...session,
                    lastMessage,
                    lastTime,
                    unreadCount: unread ? (session.unreadCount || 0) + 1 : session.unreadCount
                })
            } else {
                // 添加新会话
                state.chatSessions.push({
                    userId,
                    lastMessage,
                    lastTime,
                    unreadCount: unread ? 1 : 0
                })
            }

            // 按最后消息时间排序
            state.chatSessions.sort((a, b) => b.lastTime - a.lastTime)
        },

        // 设置当前聊天会话
        setCurrentChatSession(state, userId) {
            state.currentChatSession = userId

            // 将该用户的未读消息标记为已读
            const sessionIndex = state.chatSessions.findIndex(session => session.userId === userId)
            if (sessionIndex !== -1) {
                const session = state.chatSessions[sessionIndex]
                const unreadCount = session.unreadCount || 0

                // 更新总未读数
                state.unreadMessageCount = Math.max(0, state.unreadMessageCount - unreadCount)

                // 更新会话未读数
                state.chatSessions.splice(sessionIndex, 1, {
                    ...session,
                    unreadCount: 0
                })
            }
        },

        // 清空与指定用户的聊天记录
        clearChatMessages(state, userId) {
            if (state.chatMessages[userId]) {
                state.chatMessages[userId] = []
            }
        }
    },

    actions: {
        // 登录
        Login({ commit }, userInfo) {
            const username = userInfo.username.trim()
            const password = userInfo.password
            const uuid = userInfo.uuid
            const code = userInfo.code
            return new Promise((resolve, reject) => {
                login(username, password, uuid, code).then(res => {
                    commit('setToken', res.token)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 退出系统
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('setToken', '')
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 获取用户信息
        getInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    const user = res.user
                    commit('setUserInfo', user)
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        setTabbarActive({ commit }, index) {
            commit('setTabbarActive', index)
        },
        toggleLikePost({ commit }, postId) {
            commit('toggleLikePost', postId)
        }
    }
})